#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

#include "cmd.h"

void read_and_cmp(char *path, char *expected)
{
    int fd = open(path, O_RDONLY);

    char buff[1024];
    int count = read(fd, buff, sizeof(buff));
    buff[count] = 0;

    close(fd);
    assert(strcmp(buff, expected) == 0);
}

void test_exec_cmd()
{
    unlink("test.out");

    pid_t pid = fork();
    if (pid == 0) { 
        struct cmd cmd = {
            2, {"echo", "hello", NULL}, NULL, "test.out"
        };
        exec_cmd(&cmd);
    }
    wait(NULL);

    read_and_cmp("test.out", "hello\n");
}

// cat <test.in | sort | uniq | cat >test.out
void test_exec_pipe_cmd()
{
    unlink("test.out");

    pid_t pid = fork();
    if (pid == 0) { 
        // echo "3\n1\n2\n3\n2" | cat >log.txt
	struct cmd cmdv[4] = {
		{1, {"cat", NULL}, "test.in", NULL},
		{1, {"sort", NULL}, NULL, NULL},
		{1, {"uniq", NULL}, NULL, NULL},
		{1, {"cat", NULL}, NULL, "test.out"}
	};
        exec_pipe_cmd(4, cmdv);
    }
    wait(NULL);

    read_and_cmp("test.out", "1\n2\n3\n");
}
